import React, { useEffect, useState, useRef } from "react";
import { Layout, Table, Button, Input, Modal, Form, message, Select } from 'antd';
import { useManagePage } from '@/store/configStore';
import { useRouter } from '@/router/hooks';
import Back from '@/components/router/Back';
import dayjs from "dayjs";
import { SearchOutlined, PlusOutlined } from "@ant-design/icons";
import userService from "@/api/services/userService";
import usePermission from '@/hooks/event/usePermission';
import PasswordModal from '../components/modal/PasswordModal';

import { sha256 } from 'js-sha256';
export const hashStr = (str: string) => {
  return sha256(str);
};

import './user.css'

const { Header, Content } = Layout;

interface UserInfo {
  id: string;
  username: string;
  // role: string;
  create_time: number;
}

interface UserRole {
  id: string;
  name: string;
  code: string;
  memo: string;
}


interface CreateUserFormValues {
  username: string;
  password: string;
  confirmPassword: string;
}


interface ModifyPasswordFormValues {
  username: string;
  userId: string;
  originPassword: string;
  newPassword: string;
  confirmPassword: string;
}

const AppPage: React.FC = () => {
  const router = useRouter();
  const managePage = useManagePage();
  const { isInManager } = usePermission();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isModalPasswordVisible, setIsModalPawwsowdVisible] = useState(false);
  const [searchText, setSearchText] = useState("");
  const [userRole, setUserRole] = useState<UserRole[]>([]);
  const [userList, setUserList] = useState<UserInfo[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [loading, setLoading] = useState(false);

  const [createForm] = Form.useForm<CreateUserFormValues>();
  const [modifyPasswordForm] = Form.useForm<ModifyPasswordFormValues>();

  const checkPasswordStrength = (password: string) => {
    // 定义四种字符类型正则
    const hasUpper = /[A-Z]/.test(password);
    const hasLower = /[a-z]/.test(password);
    const hasDigit = /[0-9]/.test(password);
    const hasSpecial = /[!@#$%^&*()_+\-=$$$${};':"\\|,.<>/?]/.test(password);

    // 计算符合的条件数量
    const conditionsMet = [hasUpper, hasLower, hasDigit, hasSpecial]
      .filter(Boolean).length;

    // 长度要求 + 至少3种类型
    return password.length >= 8 && conditionsMet >= 3;
  };

  const fetchUser = async () => {
    setLoading(true);
    try {
      const data = await userService.fetchUser({
        keywords: searchText ? searchText : "",
        page: pagination?.current,
        page_size: pagination?.pageSize,
      });
      setUserList(data.list);
      setPagination({
        ...pagination,
        total: data.total,
      });
    } catch (error) {
      console.log(error);
    } finally {
      setLoading(false);
    }
  };

  const fetchUserRoles = async () => {
    setLoading(true);
    try {
      const data = await userService.getRoles();
      setUserRole(data?.roles)
    } catch (error) {
      console.log(error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUser();
    // fetchUserRoles()
  }, [pagination.current, pagination.pageSize, searchText]);

  const handleTableChange = (pagination: any) => {
    setPagination({
      current: pagination.current,
      pageSize: pagination.pageSize,
      total: pagination.total,
    });
  };

  const handleSearch = (value: string) => {
    setSearchText(value);
    setPagination({
      ...pagination,
      current: 1,
    });
  };

  const handleModifyPassword = async (values: ModifyPasswordFormValues) => {
    console.log(values)
    if (values.newPassword == values.originPassword) {
      message.error("新密码不能与原密码一致");
      return;
    }
    if (values.newPassword !== values.confirmPassword) {
      message.error("新密码和确认密码不一致");
      return;
    }

    if (!checkPasswordStrength(values.newPassword)) {
      message.error("密码必须包含大写字母、小写字母、数字、特殊符号中的至少三种且长度8位以上");
      return;
    }

    try {
      await userService.updatePassword(
        values?.userId,
        {
          new_password: hashStr(values.newPassword),
          origin_password: hashStr(values.originPassword),
        });
      message.success("用户密码修改成功");
      setIsModalPawwsowdVisible(false);
      modifyPasswordForm.resetFields();

    } catch (error) {
      console.error(error);
    }
  };

  const handleCreateUser = async (values: CreateUserFormValues) => {
    if (values.password !== values.confirmPassword) {
      message.error("密码和确认密码不一致");
      return;
    }

    if (!checkPasswordStrength(values.password)) {
      message.error("密码必须包含大写字母、小写字母、数字、特殊符号中的至少三种且长度8位以上");
      return;
    }

    try {
      await userService.createUser({
        name: values.username.trim(),
        password: hashStr(values.password),
      });
      // message.success("用户创建成功");
      setIsModalVisible(false);
      createForm.resetFields();
      fetchUser(); // 刷新用户列表

      Modal.confirm({
        title: '角色配置',
        content: (
          <div>
            <p>用户创建成功，继续为用户配置角色！</p>
          </div>
        ),
        okText: '跳转',
        cancelText: '取消',
        cancelButtonProps: {
          className: 'custom-cancel-button',
        },
        okButtonProps: {
          style: {
            backgroundColor: '#6640FF',
            borderColor: '#6640FF'
          }
        },
        onOk: async () => {
          if (isInManager) {
            router.push("/apps/permission-manage?app=role");
          } else {
            router.push("/role/manage");
          }
        },
        onCancel: () => {
          console.log('用户取消了操作');
        },
      });

    } catch (error) {
      // message.error("用户创建失败");
      console.error(error);
    }
  };

  const columns = [
    {
      title: "用户名",
      dataIndex: "username",
      align: 'center' as const,
      width: '40%',
      key: "username",

    },
    {
      title: "创建时间",
      dataIndex: "create_time",
      align: 'center' as const,
      width: '40%',
      key: "create_time",
      render: (date: string) => dayjs(date).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: "操作",
      align: 'center' as const,
      width: '20%',
      key: "action",
      render: (record: UserInfo) => (
        <div className="flex justify-center items-center gap-5">
          <Button
            type="primary"
            danger
            className="!rounded-button whitespace-nowrap"
            onClick={() => {
              let userInput = '';
              Modal.confirm({
                title: '确认删除',
                content: (
                  <div>
                    <p>您确定要删除 {record.username} 吗？请输入用户名进行确认。</p>
                    <Input placeholder="请输入用户名" className="my-2" onChange={(e) => (userInput = e.target.value)} />
                  </div>
                ),
                okText: '确定',
                cancelText: '取消',
                okButtonProps: { danger: true },
                onOk: async () => {

                  console.log(userInput)
                  console.log(record.username)
                  if (userInput && userInput === record.username) {
                    await userService.deleteUser(record.id).then(() => {
                      message.success("删除成功")
                      fetchUser();
                    })
                  } else {
                    message.error('输入的用户名不匹配，删除操作取消')
                  }
                },
                onCancel: () => {
                  console.log('用户取消了删除操作');
                },
              });
            }}
          >
            删除
          </Button>
          <Button
            type="primary"
            className="!rounded-button bg-blue-600 hover:bg-blue-700 border-none whitespace-nowrap"
            onClick={() => {
              {
                modifyPasswordForm.setFieldsValue({
                  username: record?.username,
                  userId: record?.id
                });
                setIsModalPawwsowdVisible(true)
              }
            }}
          >
            修改密码
          </Button>
        </div>
      ),
    },
  ];

  return (
    <Layout className="h-full" style={{ background: '#FBFCFF', overflowX: 'hidden' }}>
      {!isInManager && <Header style={{ background: '#FBFCFF', padding: 0, borderBottom: '1px solid #DDE5FF' }}>
        <div className="flex items-center">
          <div className="flex">
            <Back
              title={'返回'}
              onClick={() => {
                router.push(managePage);
              }}
            />
          </div>
        </div>
      </Header>}
      <Content>
        <div className="mx-auto py-6 px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center mb-8">
            <h1 className="text-2xl font-medium text-gray-900"></h1>
            <div className="flex items-center space-x-4">
              <div className="relative">
                <Input
                  placeholder="搜索"
                  allowClear
                  prefix={<SearchOutlined className="text-gray-400" />}
                  className="w-64 h-10 pl-10 pr-4 rounded-lg border-gray-200 focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
                  value={searchText}
                  onChange={(e) => handleSearch(e.target.value)}
                />
              </div>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                className="!rounded-button h-10 bg-blue-600 hover:bg-blue-700 border-none whitespace-nowrap"
                onClick={() => setIsModalVisible(true)}
              >
                新增
              </Button>
            </div>
          </div>
          <div className="bg-white rounded-lg">
            <Table
              columns={columns}
              dataSource={userList}
              rowKey="id"
              loading={loading}
              pagination={{
                ...pagination,
                showSizeChanger: true,
                showTotal: (total) => `共 ${total} 条`,
              }}
              onChange={handleTableChange}
            />
          </div>
        </div>
      </Content>

      <Modal
        title="新增用户"
        open={isModalVisible}
        onCancel={() => {
          setIsModalVisible(false);
          createForm.resetFields();
        }}
        footer={null}
      >
        <Form form={createForm} onFinish={handleCreateUser} layout="vertical" name="createUser">
          <Form.Item
            label="用户名"
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password placeholder="请输入密码" />
          </Form.Item>
          <Form.Item
            label="确认密码"
            name="confirmPassword"
            rules={[
              { required: true, message: '请确认密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password placeholder="请确认密码" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      <PasswordModal
        visible={isModalPasswordVisible}
        username={modifyPasswordForm.getFieldValue('username') || ''}
        userId={modifyPasswordForm.getFieldValue('userId') || ''}
        onCancel={() => {
          setIsModalPawwsowdVisible(false);
          modifyPasswordForm.resetFields();
        }}
        onSubmit={handleModifyPassword}
      />

    </Layout >
  );
};

export default AppPage;